<template>
  <div class="content_box">
    <form class="condition_query">
      <span class="txt">标段</span>
      <el-select class="inline-input" size="medium" v-model="bidSection" clearable placeholder="请选择">
        <el-option v-for="item in biaoduanList" :key="item.id" :label="item.name" :value="item.name" />
      </el-select>

      <span class="txt">设备类型</span>
      <el-select class="inline-input" size="medium" v-model="deviceType" clearable placeholder="请选择">
        <el-option v-for="item in deviceTypeList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" size="medium" icon="el-icon-search" style="margin-left:40px" @click="showMatainList">
        查询
      </el-button>
    </form>

    <div>
      <el-table
        :data="tableDataList"
        :height="tableHeight1"
        size="small"
        highlight-current-row
        @row-click="matainRecord"
        style="width: 100%">
        <el-table-column type="index" label="No" :index="indexMethod"></el-table-column>
        <el-table-column prop="deviceCnName" label="设备名称"></el-table-column>
        <el-table-column prop="mobilizationSerialNumber" label="进场编号"></el-table-column>
        <el-table-column prop="bidSection" label="标段"></el-table-column>
        <el-table-column prop="deviceTypeName" label="设备类型"></el-table-column>
        <el-table-column prop="deviceSource" label="设备来源"></el-table-column>
        <el-table-column prop="indexDate" label="上次保养日期">
          <template slot-scope="scope">
            <span>{{ scope.row.indexDate ? scope.row.indexDate : "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="nextDate" label="下次保养日期">
          <template slot-scope="scope">
            <span>{{ scope.row.nextDate ? scope.row.nextDate : "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="cycle" label="保养周期">
          <template slot-scope="scope">
            <span>{{ scope.row.cycle ? scope.row.cycle + scope.row.timeCompanyName : "无" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isPush" label="推送">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.warningSwitch"
              active-color="#13ce66"
              :disabled="!scope.row.nextDate && !scope.row.cycle"
              @change="changeWarningSwitch(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click.stop="editRecordInfo(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click.stop="delRecordInfo(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination class="page-wrap" :pageData="pageData" @pageNum="pageNumData" @pageSize="pageSizeData"></Pagination>
    </div>

    <!-- 维保记录 -->
    <div>
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center;">
        <span>维保记录</span>
        <el-button type="primary" size="small" @click.stop="showRecordModel">添加维保记录</el-button>
      </div>
      <el-table
        :data="pointList"
        :height="tableHeight2"
        size="small"
        style="width: 100%;">
        <el-table-column type="index" label="No" :index="indexMethod"></el-table-column>
        <el-table-column prop="type" label="维修/保养">
          <template slot-scope="scope">
            {{ scope.row.type | chargeType }}
          </template>
        </el-table-column>
        <el-table-column prop="maintenanceTime" label="维保时间">
          <template slot-scope="scope">
            {{ scope.row.maintenanceTime | changeDate }}
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="维养单位"></el-table-column>
        <el-table-column prop="approvalResults" label="维养结论"></el-table-column>
        <el-table-column prop="report" label="检定证书编号"></el-table-column>
        <el-table-column prop="repairman" label="登记人"></el-table-column>
        <el-table-column prop="createTime" label="登记时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | changeDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="updateData(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click="delData(scope.row)">删除</el-button>
            <el-button type="text" size="small" @click="detailModal(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination class="page-wrap" :pageData="page" @pageNum="pageNumData" @pageSize="pageSizeData"></Pagination>
    </div>

    <!-- 维保记录弹窗 -->
    <el-dialog :title="pointTitle" :visible.sync="dialogVisible" width="550px">
      <div style="text-align: center;">
        <div class="info-modal row-item" v-show="newId == 0">
          <span class="text">进场编号：</span>
          <el-select v-model="deviceListId" style="width: 260px;" size="medium" placeholder="请选择">
            <el-option
              v-for="item in tableDataList"
              :key="item.id"
              :label="item.mobilizationSerialNumber"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div class="info-modal row-item">
          <span class="text">维保类型：</span>
          <el-select style="width: 260px" size="medium" v-model="form.type" clearable placeholder="请选择">
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.type"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <div class="info-modal row-item">
          <span class="text">维保时间：</span>
          <el-date-picker
            style="width: 260px;"
            size="medium"
            v-model="form.maintenanceTime"
            type="date"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期">
          </el-date-picker>
        </div>
        <div class="info-modal row-item">
          <span class="text">检定证书编号：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="form.report"></el-input>
        </div>
        <div class="info-modal row-item">
          <span class="text">登记人：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="form.repairman"></el-input>
        </div>
        <div class="info-modal row-item">
          <span class="text">维养单位：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="form.unit"></el-input>
        </div>
        <div class="info-modal row-item">
          <span class="text">维养结论：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入"
                    v-model.trim="form.approvalResults"></el-input>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMatain">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置保养时间 -->
    <el-dialog title="设置保养日期" :visible.sync="upkeepDialog" width="550px">
      <div style="text-align: center">
        <div class="info-modal row-item">
          <span class="text">下次保养日期：</span>
          <el-date-picker
            style="width: 260px;"
            size="medium"
            v-model="formUpkeep.nextDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期">
          </el-date-picker>
        </div>
        <div class="info-modal row-item">
          <span class="text">保养周期：</span>
          <el-input style="width: 126px;" size="medium" placeholder="请输入数字" v-model.trim="formUpkeep.cycle" />
          <el-select v-model="formUpkeep.timeCompany" style="width: 130px;" size="medium" placeholder="请选择">
            <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="info-modal row-item">
          <span class="text">推送人姓名：</span>
          <el-input style="width: 260px;" size="medium" placeholder="请输入" v-model.trim="formUpkeep.pushPerson"/>
        </div>
        <div class="info-modal row-item">
          <span class="text">推送人电话：</span>
          <el-input
            style="width: 260px;"
            size="medium"
            maxlength="11"
            show-word-limit
            placeholder="请输入"
            v-model.trim="formUpkeep.pushTel"/>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="upkeepDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUpkeepInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "../Pagination";
import HttpInterface from "../../../util/httpInterface";
import {mapState} from "vuex";
import Constants from "../../../util/constants";
import { messageBox } from "../../../util/utils";

export default {
  name: "DeviceMaintain",
  components: {
    Pagination
  },
  data() {
    return {
      bidSection: "",
      deviceType: "",
      deviceTypeList: [
        {value: '1-1', label: '一般设备'},
        {value: '1-2', label: '主要设备'},
        {value: '1-3', label: '特种设备'},
        {value: '1-4', label: '关键设备'},
      ],
      deviceSourceId: '',
      deviceListId: "",
      deviceSourceList: [],
      tableDataList: [],
      pageData: {
        total: 0,
        pageNum: 1,
        pageSize: 20
      },
      page: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      pointList: [],
      tableHeight1: '',
      tableHeight2: '',
      dialogVisible: false,
      pointTitle: '添加维保记录',
      form: {
        type: '',
        approvalResults: '',
        unit: '',
        report: '',
        repairman: '',
        maintenanceTime: ""
      },
      typeList: [
        {value: '0', type: "维护"},
        {value: '1', type: "保养"}
      ],
      timeList: [
        {value: '1', label: "日"},
        {value: '2', label: "周"},
        {value: '3', label: "月"},
        {value: '4', label: "年"},
      ],
      formUpkeep: {
        nextDate: "",
        timeCompany: "1",
        cycle: "",
        pushPerson: "",
        pushTel: ""
      },
      newId: "0",
      upkeepDialog: false
    }
  },

  computed: {
    ...mapState(["biaoduanList"])
  },

  created() {
    this.getTableHeight()
  },

  filters: {
    chargeType(val) {
      if (val && val == "1") {
        return val = "保养"
      } else {
        return val = "维护"
      }
    }
  },

  mounted() {
    let _this = this;
    let resizeFlag = null;
    window.onresize = () => {
      resizeFlag && clearTimeout(resizeFlag);
      resizeFlag = setTimeout(() => {
        _this.getTableHeight();
        resizeFlag = null;
      }, 120);
    };
  },

  beforeDestroy() {
    window.onresize = null;
  },

  methods: {
    getTableHeight() {
      let num = 156;  // 表格距离窗口顶的top 与 bottom之和
      let tableNum = (window.innerHeight - num) / 2;  // 有两个表格
      this.tableHeight1 = tableNum - 65;  // 第一个表格高一点
      this.tableHeight2 = tableNum - 82;  // 第二个表格低一点
    },

    indexMethod(index) {
      return index + 1;
    },

    pageNumData(page) {
      this.pageData.pageNum = Number(page);
      this.showMatainList();
    },

    pageSizeData(page) {
      this.pageData.pageSize = Number(page);
      this.showMatainList();
    },

    //设备列表
    showMatainList() {
      var _this = this
      var params = {
        page: _this.pageData.pageNum,
        size: _this.pageData.pageSize
      }
      if (this.bidSection) {
        params.bidSection = this.bidSection;
      }
      if (this.deviceType) {
        params.deviceType = this.deviceType;
      }
      HttpInterface.requestGet(this, HttpInterface.URL_MATAINRECORD_FINDPAGE, params, function (res) {
        var { rows, total } = res.data.other
        rows.forEach(item => {
          item.deviceTypeName = Constants.DEVICE_TYPE_LIST[item.deviceType];
          if (item.nextDate) {
            item.nextDate = item.nextDate.slice(0, 10);
          }
          if (item.timeCompany) {
            item.timeCompanyName = " " + Constants.TIME_COMPANY[item.timeCompany];
          } else {
            item.timeCompanyName = "";
          }
          if (item.isPush) {
            item.warningSwitch = item.isPush == 0 ? false : true;  // 1 推送    0 不推送
          } else {
            item.warningSwitch = false;
          }
        })
        _this.tableDataList = rows;
        _this.pageData.total = total;
      }, null)
    },

    //维保记录列表
    matainRecord(row) {
      this.row = row;
      var _this = this
      var params = {
        page: _this.pageData.pageNum,
        size: _this.pageData.pageSize,
        maintenanceRecordId: row.id
      }
      HttpInterface.requestGet(this, HttpInterface.URL_MATAINRECORD_DETAIL_FINDPAGE, params, function (res) {
        var data = res.data.other
        _this.pointList = data.rows;
        _this.page.total = data.total;
      }, null)
    },

    //添加维保记录
    showRecordModel() {
      this.dialogVisible = true
      this.pointTitle = '添加维保记录'
      this.newId = "0";
      this.deviceListId = "";
      this.form = {
        type: '',
        approvalResults: '',
        unit: '',
        report: '',
        repairman: '',
        maintenanceTime: ""
      }
    },

    // 编辑维保记录
    editRecordInfo(row) {
      this.upkeepDialog = true;
      this.formUpkeep = {
        nextDate: row.nextDate,
        cycle: row.cycle,
        pushPerson: row.pushPerson,
        pushTel: row.pushTel,
        timeCompany: row.timeCompany ? row.timeCompany + "" : "1",
        id: row.id,
        mechanicalDeviceId: row.mechanicalDeviceId
      };
    },

    verifyFormInfo() {
      let integer = /^[1-9]\d*$/;
      let tel = /^((\+?[0-9]{1,4})|(\(\+86\)))?(13[0-9]|14[57]|15[012356789]|17[03678]|18[0-9]|19[0-9])\d{8}$/;
      let { nextDate, cycle, pushPerson, pushTel } = this.formUpkeep;
      if (!nextDate) {
        this.warningMessage("请选择下次保养日期");
        return false;
      }
      if (!cycle) {
        this.warningMessage("请输入保养周期");
        return false;
      }
      if (!integer.test(cycle)) {
        this.warningMessage("保养周期为正整数");
        return false;
      }
      if (!pushPerson) {
        this.warningMessage("请输入推送人姓名");
        return false;
      }
      if (!pushTel) {
        this.warningMessage("请输入推送人电话");
        return false;
      }
      if (!tel.test(pushTel)) {
        this.warningMessage("请确认输入的电话格式");
        return false;
      }
      return true;
    },

    addUpkeepInfo() {
      if (!this.verifyFormInfo()) {
        return true
      }
      let _this = this;
      let params = this.formUpkeep;
      HttpInterface.requestPost(this, HttpInterface.URL_MATAINRECORD_RECORD_UPDATE, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.upkeepDialog = false;
          _this.successMessage("操作成功！");
          _this.showMatainList();
        } else {
          _this.errorMessage('操作失败！');
        }
      }, null, false)
    },

    changeWarningSwitch(row) {
      if (!row.pushTel) {
        this.errorMessage("当前设备没有设置推送人电话，请设置推送人电话后再设置是否推送");
        this.showMatainList();
        return;
      }
      let _this = this;
      let params = {
        id: row.id,
        mechanicalDeviceId: row.mechanicalDeviceId,
        isPush: !row.isPush || row.isPush == 0 ? 1 : 0
      };
      HttpInterface.requestPost(this, HttpInterface.URL_MATAINRECORD_RECORD_UPDATE, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.upkeepDialog = false;
          _this.successMessage("操作成功！");
          _this.showMatainList();
        } else {
          _this.errorMessage('操作失败！');
        }
      }, null, false)
    },

    // 删除维保记录
    delRecordInfo(id) {
      let _this = this;
      messageBox(() => {
        let params = {
          id: id
        };
        HttpInterface.requestGet(this, HttpInterface.URL_MATAINRECORD_DELETE, params, function (res) {
          let data = res.data;
          if (data.success) {
            _this.successMessage("删除成功！");
            _this.showMatainList();
          } else {
            _this.errorMessage("删除失败！");
          }
        }, null)
      })
    },

    // 确认添加/修改 维保记录
    addMatain() {
      var _this = this
      this.form.type = this.form.type = "保养" ? "1" : "0";
      var params = this.form;
      params.maintenanceRecordId = this.deviceListId || this.form.maintenanceRecordId;
      var url = (_this.newId == 0) ? HttpInterface.URL_MATAINRECORD_INSERT : HttpInterface.URL_MATAINRECORD_UPDATE;
      HttpInterface.requestPost(this, url, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.dialogVisible = false;
          _this.successMessage("操作成功！");
          _this.matainRecord(_this.row);
        } else {
          _this.errorMessage("操作失败！");
        }
      }, null, false)
    },

    //修改
    updateData(row) {
      this.dialogVisible = true
      this.pointTitle = '修改维保记录'
      let _this = this;
      _this.newId = row.id
      var params = {
        id: _this.newId
      }
      HttpInterface.requestGet(this, HttpInterface.URL_MATAINRECORD_SELECTBYKEY, params, function (res) {
        let data = res.data;
        if (data.success) {
          _this.form = data.other
          _this.form.type = _this.form.type == "1" ? "保养" : "维护";
        } else {
          _this.errorMessage("获取数据失败！");
        }
      }, null)
    },

    //删除
    delData(row) {
      let _this = this;
      messageBox(() => {
        let params = {
          id: row.id
        };
        HttpInterface.requestGet(this, HttpInterface.URL_DETAILS_DELETE, params, function (res) {
          let data = res.data;
          if (data.success) {
            _this.successMessage("删除成功！");
            _this.matainRecord(_this.row)
          } else {
            _this.errorMessage("删除失败！");
          }
        }, null)
      })
    },

    //详情
    detailModal(row) {
      let data = {
        row: this.row,
        rowData: row
      };
      this.$emit('maintain', data)
    }
  }
}
</script>

<style scoped lang="scss">
.condition_query {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  .txt {
    margin-right: 10px;
    font-size: 14px;
  }
}

.inline-input {
  width: 150px;
  margin-right: 22px;
}

.info-modal {
  margin: 20px 30px 20px 0;

  .text {
    font-size: 14px;
    margin-right: 10px;
    width: 100px;
    display: inline-block;
    text-align: right;
  }
}

.page-wrap {
  margin-top: 10px !important;
}

.tabel-btn {
  padding: 0 !important;
}

.row-item {
  margin: 18px 0;

  &:first-child {
    margin-top: 10px;
  }

  &:last-child {
    margin-bottom: 5px;
  }

  .text {
    width: 100px;
    display: inline-block;
    text-align: right;
    margin-right: 4px;
  }
}
</style>
